//
//  Comments_VC.m
//  WorldOfFacts_V2
//
//  Created by Demjanko Denis on 12.12.12.
//  Copyright (c) 2012 it-dimension. All rights reserved.
//

#import "Comments_VC.h"
#import "CommentsCell.h"
#import "Service.h"
#import "UserManager.h"

@implementation Comments_VC

@synthesize inputToolbar;

#define kStatusBarHeight 20
#define kDefaultToolbarHeight 40
#define kKeyboardHeightPortrait 216

#pragma mark - View Life

@synthesize fact_id;

- (void)setNavTitle:(NSString *)title
{
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        
        titleView.textColor = [UIColor colorWithRed:187.0f/255.0f green:187.0f/255.0f blue:187.0f/255.0f alpha:1.0f]; // Change to desired color
        
        self.navigationItem.titleView = titleView;
    }
    
    titleView.text = title;
    [titleView sizeToFit];
}

- (void)viewDidLoad{
    [super viewDidLoad];
    [self setupBackButton];
    [self setNavTitle:@"Комментарии"];
    
    [self showHUD];
    [self performSelector:@selector(getComments) withObject:nil afterDelay:0.2f];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ON_PHOTOBROWSER_DONE" object:nil];

	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


-(void)setupBackButton{
    self.navigationItem.leftBarButtonItem = nil;
    
    UIButton *back_btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [back_btn setFrame:CGRectMake(0, 0, 62, 34)];
    [back_btn setBackgroundImage:[UIImage imageNamed:@"back-btn"] forState:UIControlStateNormal];
    [back_btn setBackgroundImage:[UIImage imageNamed:@"back-btn1"] forState:UIControlStateHighlighted];
    [back_btn addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem =  [[UIBarButtonItem alloc]initWithCustomView:back_btn];
}

-(void)setupWriteIcon{
    UIButton *menu_btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [menu_btn setFrame:CGRectMake(0, 0, 43, 34)];
    [menu_btn setBackgroundImage:[UIImage imageNamed:@"write_icon"] forState:UIControlStateNormal];
    [menu_btn setBackgroundImage:[UIImage imageNamed:@"write_icon_selected"] forState:UIControlStateHighlighted];
    [menu_btn addTarget:self action:@selector(onComment) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:menu_btn]; 
}

- (void)loadView{
    [super loadView];
    
    self.inputToolbar = [[UIInputToolbar alloc] initWithFrame:CGRectMake(0, 377, self.view.frame.size.width, kDefaultToolbarHeight)];
    self.inputToolbar.delegate = self;
    self.inputToolbar.textView.placeholder = @"Новый комментарий";
    [self.view addSubview:self.inputToolbar];
}

#pragma mark - IBActions

-(void)onBack{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)onComment{
    self.inputToolbar.alpha = 1.0f;
    
    [self.inputToolbar.textView performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0.5f];
}

#pragma mark - UITableView

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGSize expectedCommentSize = [[[comments objectAtIndex:indexPath.row] valueForKey:@"comment"] sizeWithFont:[UIFont systemFontOfSize:14.0f] 
                                                               constrainedToSize:CGSizeMake(230, 9999) 
                                                                   lineBreakMode:UILineBreakModeWordWrap];
    
    if(expectedCommentSize.height+65<80)
        return 100;
    
    return expectedCommentSize.height+65;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return comments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    
    CommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[CommentsCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];                        
    }
    
    [cell setComment:[comments objectAtIndex:indexPath.row]];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

#pragma mark - inputToolbar

- (void)keyboardWillShow:(NSNotification *)notification {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	CGRect frame = self.inputToolbar.frame;
    frame.origin.y = self.view.frame.size.height - frame.size.height - kKeyboardHeightPortrait;
	self.inputToolbar.frame = frame;
	[UIView commitAnimations];
    
    keyboardIsVisible = YES;    
}

- (void)keyboardWillHide:(NSNotification *)notification {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.3];
	CGRect frame = self.inputToolbar.frame;
    frame.origin.y = self.view.frame.size.height - frame.size.height;
	self.inputToolbar.frame = frame;
	[UIView commitAnimations];
    
    keyboardIsVisible = NO;
}

-(void)inputButtonPressed:(NSString *)inputText{    
    if([[UserManager currentUser] auth]==0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:@"Для отправки комментариев необходима учетная запись.\nВы можете авторизироваться, перейдя на вкладку настройки." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    [self showHUD];
    [self performSelector:@selector(addNewComment:) withObject:[NSString stringWithString:inputText] afterDelay:0.3f];
}

#pragma mark - service & local

-(void)addNewComment:(NSString*)text{
    [[Service sharedManeger] sendComment:fact_id comment:text withHandler:^(NSData *response, NSError *error) {
        [self hideHUD];
                        
        if(error){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            return;  
        }
        else{      
            NSDateFormatter *form = [[NSDateFormatter alloc] init];
            [form setDateFormat:@"dd/MM/yyyy"];
            
            NSString *date = [form stringFromDate:[NSDate date]];
            
            NSMutableDictionary *cmnt = [NSMutableDictionary dictionary];
            [cmnt setValue:text forKey:@"comment"];
            [cmnt setValue:date forKey:@"date"];
            [cmnt setValue:[[UserManager currentUser] name] forKey:@"user_name"];
            [cmnt setValue:[[UserManager currentUser] ava].absoluteString forKey:@"user_photo"];
            
            [comments addObject:cmnt];
            [table insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:comments.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
            [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:comments.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 
        }
    }];
}

-(void)getComments{
    comments = [[NSMutableArray alloc] init];

    [[Service sharedManeger] getComments:fact_id withHandler:^(NSData *response, NSError *error) {
        [self performSelector:@selector(hideHUD) withObject:nil afterDelay:0.0f];
                
        if(error){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Ошибка" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            return;  
        }
        else{
            [comments addObjectsFromArray:[response objectFromJSONData]];
                        
            [self performSelector:@selector(reloadTable) withObject:nil afterDelay:0.2f];            
        }
    }];
}

-(void)reloadTable{
    if(comments.count==0)
        return;
    
    [table reloadData];
    [table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:comments.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

#pragma mark - loading

-(void)showHUD{
    hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    hud.dimBackground = YES;
    [hud show:YES];
    [self.navigationController.view addSubview:hud];
}

-(void)hideHUD{
    [hud show:FALSE];
    [hud removeFromSuperview];
	hud = nil;
}

#pragma mark - Memory Management

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}

-(void)dealloc{
    table = nil;
    comments = nil;
    inputToolbar = nil;
}

@end
